package com.http2;

import java.nio.ByteBuffer;

public class Http2Frame {
	public int length;      // 帧长度
    public byte type;       // 帧类型（0x1:HEADERS, 0x0:DATA）
    public byte flags;      // 标志位
    public int streamId;     // Stream ID
    public byte[] payload;  // 数据负载

    // 序列化为ByteBuffer
    public ByteBuffer serialize() {
        ByteBuffer buffer = ByteBuffer.allocate(10 + length);
        buffer.putInt(length);
        buffer.put(type);
        buffer.put(flags);
        buffer.putInt(streamId);
        buffer.put(payload);
        buffer.flip();
        return buffer;
    }

    // 从ByteBuffer解析
    public static Http2Frame deserialize(ByteBuffer buffer) {
        Http2Frame frame = new Http2Frame();
        frame.length = buffer.getInt();
        frame.type = buffer.get();
        frame.flags = buffer.get();
        frame.streamId = buffer.getInt();
        frame.payload = new byte[frame.length];
        buffer.get(frame.payload);
        return frame;
    }
}